import time
from Acquisition import aq_inner, aq_base
from zope.interface import implements
from zope.component import getMultiAdapter

from plone.portlets.interfaces import IPortletDataProvider
from plone.app.portlets.portlets import base
from Products.Five.browser import BrowserView

from zope import schema
from zope.formlib import form
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate

from ely.portlets.iframe import IFramePortletMessageFactory as _


class IIFramePortlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    title = schema.TextLine(title=_(u"Title"),
                             description=_(u"A title to show in the admin UI"),
                             required=True)

    tal = schema.Text(title=_(u"TAL code"),
                      description=_(u"TAL code which will be executed when the portlet is rendered"),
                      required=True, default=u"No Content")

    width = schema.TextLine(title=_(u"width"),
                            description=_(u"width of iframe as a string, so use px,% etc"),
                            required=True, default=u"0px")

    height = schema.TextLine(title=_(u"height"),
                            description=_(u"height of iframe as a string, so use px,% etc"),
                            required=True, default=u"0px")

class Assignment(base.Assignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(IIFramePortlet)

    title = u"iframe portlet"
    assignment_context_path = None
    timestamp = ''

    def __init__(self, title=u"", tal=u"",
                 assignment_context_path=None,
                 width=u"",
                 height=u""):
        self.title = title
        self.width = width
        self.height = height
        self.assignment_context_path = assignment_context_path
        self.pt = ZopePageTemplate(id='__tal_portlet__')
        self.tal = tal
        self.update_timestamp()

    def _get_tal(self):
        return self.pt.read()
    def _set_tal(self, value):
        self.pt.pt_edit(value, 'text/html')
    tal = property(_get_tal, _set_tal)

    def update_timestamp(self):
        self.timestamp = str(int(time.time()))

def assignment_modified_event_hander(context, event):
    context.update_timestamp()


class Renderer(base.Renderer):
    """Portlet renderer.

    This is registered in configure.zcml. The referenced page template is
    rendered, and the implicit variable 'view' will refer to an instance
    of this class. Other methods can be added and referenced in the template.
    """

    render = ViewPageTemplateFile('iframeportlet.pt')

    @property
    def srcurl(self):
        state=getMultiAdapter((self.context, self.request),
                              name="plone_portal_state")
        portal=state.portal()
        assignment_url = portal.unrestrictedTraverse(
                self.data.assignment_context_path).absolute_url()
        return '%s/%s/@@iframeportletcontent?ts=%s' %(assignment_url,
                                                      self.data.__name__,
                                                      self.data.timestamp)


class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(IIFramePortlet)

    def create(self, data):
        data['assignment_context_path'] = '/'.join(
            self.context.__parent__.getPhysicalPath())
        return Assignment(**data)


class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(IIFramePortlet)


class TALView(BrowserView):
    """
    This is the src we refer to from the tal
    """

    template = ViewPageTemplateFile('talview.pt')

    def __call__(self):
        context = aq_inner(self.context)
        pt = aq_base(context.pt).__of__(context)
        self.request.response.setHeader('Cache-Control','public,max-age=86400')
        return self.template(pt=pt)
